"use client";

import { useParams } from "next/navigation";
import { useEffect, useRef, useState } from "react";
import { useApiClient } from "../../../lib/apiClient";
import { useAudio } from "../../components/AudioContext";
import LyricsPanel from "../../components/LyricsPanel";
import Playbar from "../../components/Playbar";
import SongFeed from "../../components/SongFeed";
import SongCard from "../../SongCard";

export default function StylePage() {
  const params = useParams();
  const style = params.style as string;
  const [songs, setSongs] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const apiClient = useApiClient();
  const { currentSong, playSong, audioRef } = useAudio();
  const songRefs = useRef<(HTMLDivElement | null)[]>([]);

  useEffect(() => {
    const fetchSongs = async () => {
      setLoading(true);
      setError(null);
      try {
        const { data, error: apiError } = await apiClient.POST("/api/search", {
          body: {
            search_queries: [
              {
                name: "tag_song",
                search_type: "tag_song",
                term: style,
                from_index: 0,
                rank_by: "most_relevant",
              },
            ],
          },
        });
        if (apiError) throw new Error(apiError);
        // The response is { result: { [name]: { result: [...] } } }
        const foundSongs = data?.result?.["tag_song"]?.result || [];
        setSongs(foundSongs);
      } catch (err) {
        setError(err instanceof Error ? err.message : "Failed to load songs");
      } finally {
        setLoading(false);
      }
    };
    if (style) fetchSongs();
  }, [style, apiClient]);

  // Play next song and scroll to it
  const playNextSong = () => {
    if (!songs || !currentSong) return;
    const idx = songs.findIndex((s) => s.id === currentSong.id);
    if (idx !== -1 && idx < songs.length - 1) {
      const nextSong = songs[idx + 1];
      playSong(nextSong);
      // Scroll next card into view
      setTimeout(() => {
        songRefs.current[idx + 1]?.scrollIntoView({
          behavior: "smooth",
          block: "center",
        });
      }, 200);
    }
  };

  // Attach onEnded handler
  useEffect(() => {
    const audio = audioRef.current;
    if (!audio) return;
    const handleEnded = () => playNextSong();
    audio.addEventListener("ended", handleEnded);
    return () => {
      audio.removeEventListener("ended", handleEnded);
    };
  }, [audioRef, currentSong, songs]);

  return (
    <>
      <div className="min-h-screen bg-gradient-to-b from-background to-background/95">
        <div className="max-w-2xl pl-8 pr-4 py-8">
          <h1 className="text-2xl font-bold mb-6 text-foreground capitalize">
            {decodeURIComponent(style)}
          </h1>
          <SongFeed
            songs={songs}
            loading={loading}
            error={error}
            currentSong={currentSong}
            playSong={playSong}
            SongComponent={SongCard}
            emptyMessage={
              loading
                ? undefined
                : `No songs found for style "${decodeURIComponent(style)}".`
            }
          />
        </div>
      </div>
      <LyricsPanel />
      <Playbar />
    </>
  );
}
